package com.micro.magupe;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;

import com.micro.magupe.sharding.datasource.ShardingDataSource;
import com.micro.magupe.sharding.rule.ShardingRule;

public class MicroMagupeShardingApplication {

	public static void main(String[] args) throws SQLException {
    	BasicDataSource ds0 = new BasicDataSource();
		ds0.setDriverClassName("com.mysql.jdbc.Driver");
		ds0.setUrl("jdbc:mysql://127.0.0.1:3306/micro_magupe_log_master_dev?useUnicode=true&characterEncoding=utf8&useSSL=false");
		ds0.setUsername("root");
		ds0.setPassword("880204");
		
    	BasicDataSource ds1 = new BasicDataSource();
		ds1.setDriverClassName("com.mysql.jdbc.Driver");
		ds1.setUrl("jdbc:mysql://127.0.0.1:3306/micro_magupe_log_master_dev?useUnicode=true&characterEncoding=utf8&useSSL=false");
		ds1.setUsername("root");
		ds1.setPassword("880204");
		
		Map<String, DataSource> dataSourceMap = new HashMap<String, DataSource>();
		dataSourceMap.put("ds0", ds0);
		dataSourceMap.put("ds1", ds1);
		
		ShardingRule rule = new ShardingRule(new ArrayList<String>(Arrays.asList(new String[] {"ds0", "ds1"})), 
				new ArrayList<String>(Arrays.asList(new String[] {"sys_log:0-9:id%10"})), "id%2");
		ShardingDataSource dataSource = new ShardingDataSource(dataSourceMap, rule);
    	
		try(Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement()){
            String sql = "select * from sys_log";
            ResultSet rs = stmt.executeQuery(sql);
            while(rs.next()){
            	System.err.println(rs.getLong(1));
    		}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			dataSource.close();
		}
	}

}

